﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using LyyCMS.Core;
using LyyCMS.Core.Models;
using LyyCommon;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace LyyCMS.Web.Areas.Dash.Controllers
{
    [Area("Dash")]
    [Route("Dash/[controller]/[action]")]
    public class ArticlesController : BaseController
    {

        public ArticlesController(ILogger<BaseController> loggger, LyyCMS.Core.LyyCMSEntities lyyCMSEntities) : base(loggger, lyyCMSEntities)
        {
        }

        // GET: Dash/Articles
        public async Task<IActionResult> Index()
        {
            //var lyyCMSEntities = _context.Articles.Include(a => a.Category);
            //return View(await lyyCMSEntities.ToListAsync());
            return View(await _context.Articles.ToListAsync());            
            
        }

        // GET: Dash/Articles/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var article = await _context.Articles
                .Include(a => a.Category)
                .FirstOrDefaultAsync(m => m.Id == id);
            if (article == null)
            {
                return NotFound();
            }

            return View(article);
        }

        // GET: Dash/Articles/Create
        public IActionResult Create()
        {
            //ViewData["ArticleCategoryId"] = new SelectList(_context.ArticleCategories, "Id", "Title");
            return View();
        }

        // POST: Dash/Articles/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Title,ArticleCategoryId,ImgUrl,Url,Summary,Content,SortId,Id")] Article article)
        {
            base.GetSession(HttpContext);
            var m = article;
            article.Category = _context.ArticleCategories.FirstOrDefault(x=>x.Id==article.ArticleCategoryId);
            article.CreatorUserId = session_uid;
            article.Click = 1;
            article.CreationTime = DateTime.Now;
            article.IsDeleted = false;
            article.LastModificationTime = DateTime.Now;
            article.LastModifierUserId = session_uid;
            
            if (ModelState.IsValid)
            {
                
                _context.Add(article);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            var msg = string.Empty;
            foreach (var value in ModelState.Values)
            {
                if (value.Errors.Count > 0)
                {
                    foreach (var error in value.Errors)
                    {
                        msg = msg + error.ErrorMessage;
                    }
                }
            }
            
            ViewData["ArticleCategoryId"] = new SelectList(_context.ArticleCategories, "Id", "Title", article.ArticleCategoryId);
            return View(article);
        }

        // GET: Dash/Articles/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var article = await _context.Articles.FindAsync(id);
            if (article == null)
            {
                return NotFound();
            }
            ViewData["ArticleCategoryId"] = new SelectList(_context.ArticleCategories, "Id", "Title", article.ArticleCategoryId);
            return View(article);
        }

        // POST: Dash/Articles/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("Title,ArticleCategoryId,Click,ImgUrl,Url,Summary,Content,SortId,Id")] Article article)
        {
            if (id != article.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    base.GetSession(HttpContext);
                    article.LastModificationTime = DateTime.Now;
                    article.LastModifierUserId = session_uid;
                    _context.Update(article);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ArticleExists(article.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            ViewData["ArticleCategoryId"] = new SelectList(_context.ArticleCategories, "Id", "Title", article.ArticleCategoryId);
            return View(article);
        }

        // GET: Dash/Articles/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var article = await _context.Articles
                .Include(a => a.Category)
                .FirstOrDefaultAsync(m => m.Id == id);
            if (article == null)
            {
                return NotFound();
            }

            return View(article);
        }

        // POST: Dash/Articles/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var article = await _context.Articles.FindAsync(id);
            _context.Articles.Remove(article);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool ArticleExists(int id)
        {
            return _context.Articles.Any(e => e.Id == id);
        }
    }
}
